using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.PageFlow;
using Microsoft.Practices.PageFlow.Utils;

namespace WCSFContrib.PageFlow.Xml
{
    public class XmlPageFlowRuntime
    {
        private IXmlPageFlowInstanceStore _xmlPageFlowInstanceStore;

        public XmlPageFlowRuntime(IXmlPageFlowInstanceStore xmlPageFlowInstanceStore)
        {
            _xmlPageFlowInstanceStore = xmlPageFlowInstanceStore;
        }

        public virtual XmlPageFlowInstance CreatePageFlow(Type pageFlowType)
        {
            XmlPageFlowInstance instance = new XmlPageFlowInstance(Guid.NewGuid(), pageFlowType, this);
            _xmlPageFlowInstanceStore.Add(instance);
            return instance;
        }

        public virtual XmlPageFlowInstance GetPageFlow(Guid instanceId)
        {
            XmlPageFlowInstance instance = _xmlPageFlowInstanceStore.Get(instanceId);

            if (instance != null)
            {
                instance.Runtime = this;
            }

            return instance;
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
        public virtual void Terminate(XmlPageFlowInstance instance)
        {
            Guard.ArgumentNotNull(instance, "instance");
            _xmlPageFlowInstanceStore.Remove(instance.InstanceId);
        }

        public virtual void Persist(XmlPageFlowInstance instance)
        {
            Guard.ArgumentNotNull(instance, "instance");
            _xmlPageFlowInstanceStore.Update(instance);
        }
    }
}
